package com.imooc.service.impl;


import com.imooc.mapper.*;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;


    @Override
    public boolean queryUsernameIsExist(String username) {
        Example e = new Example(Users.class);
        Example.Criteria c = e.createCriteria();

        c.andEqualTo("username",username);

        e.orderBy("username").desc();

        List<Users> users = usersMapper.selectByExample(e);


        if(users.size() == 0){
            return false;
        }else {
            return true ;
        }

    }

    @Override
    public Users queryUserForLogin(String username, String pwd) {

        Example e = new Example(Users.class);
        Example.Criteria c = e.createCriteria();

        c.andEqualTo("username",username);
        c.andEqualTo("password",pwd);
        e.orderBy("username").orderBy("password").desc();

        List<Users> users = usersMapper.selectByExample(e);

        if(users.size() == 0){
            return null;
        }else {
            return users.get(0) ;
        }
    }

    @Override
    public Users saveUser(Users users)  {
        if(users.getNickname() == null || users.getUsername() == null || users.getPassword() == null || users.getPassword().equals("") || users.getUsername().equals("") || users.getNickname().equals("")){
            return  null;
        }
        int num = (int)(Math.random()*1000)+1;
        users.setAvatar("https://unsplash.it/800/600?image=" + String.valueOf(num) );
        users.setCreatetime(new Date());
        int id = usersMapper.insertUser(users);
        users.setId(id);
        return users ;

    }

    @Override
    public List<Users> getAlllContact(Integer userId) {

        return usersMapper.selectAllNickName(userId);

    }

    @Override
    public Users getUser(String username) {
       return usersMapper.getUsername(username);
    }

    @Override
    public boolean addFriend(int userId , int AcceptId){

        if(userId == AcceptId){
            return false;
        }

        List<Users>  list = getAlllContact(userId);

        for(Users item : list){

            if(item.getId() == AcceptId){
                return false;
            }
        }

        usersMapper.addFriend( userId , AcceptId);
        usersMapper.addFriend( AcceptId , userId );
        return true ;

    }


}
